const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("goods-records");
module.exports = class RecordService extends Service {
  async add(){
		const ctx=this.ctx
		const time=(new Date()).getTime()
		ctx.data.user_id=ctx.uid
		ctx.data.create_date=time
		ctx.data.update_date=time
		const res=await collection.where({
			goods_id:ctx.data.goods_id,
			sku_id:ctx.data.sku_id,
			user_id:ctx.uid
		}).get();
		if(res.affectedDocs>0){
			const res1=await collection.where({
				goods_id:ctx.data.goods_id,
				sku_id:ctx.data.sku_id,
				user_id:ctx.uid
			}).update({
				update_date:time
			})
			if(res1.affectedDocs>0){
				return response.success(res1.updated);
			}else{
				return response.fail('更新失败');
			}
			return res1;
		}
  	const res2=await collection.add(ctx.data);
		if(res2.id){
			return response.success(res2);
		}else{
			return response.fail('添加失败');
		}
  }
  async list(){
  	const { ctx, service } = this;
		const year=(new Date()).getFullYear()
		const start_time=(new Date(year-1,0,1)).getTime()
  	const res=await collection.where({
  		user_id:ctx.uid,
			update_date:dbCmd.gt(start_time)
  	}).orderBy('update_date','desc').get();
  	if(res.affectedDocs>=0){
  		return response.success(res.data);
  	}else{
  		return response.fail('查询失败');
  	}
  }
  async delete(){
		const ctx=this.ctx
  	const res=await collection.where({
			_id: dbCmd.in(ctx.data.ids)
		}).remove();
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('删除失败');
		}
  }
};